package com.feiyu.sys.filter

import com.alibaba.fastjson.JSONObject
import com.feiyu.sys.jwt.Jwt
import com.feiyu.sys.jwt.TokenState
import groovy.util.logging.Slf4j
import org.springframework.core.annotation.Order

import javax.servlet.Filter
import javax.servlet.FilterChain
import javax.servlet.FilterConfig
import javax.servlet.ServletException
import javax.servlet.ServletRequest
import javax.servlet.ServletResponse
import javax.servlet.annotation.WebFilter
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import static com.feiyu.sys.jwt.TokenState.*


/**
 * Created by zdy on 2017/12/1.
 */
@Slf4j
@Order(1)
@WebFilter(filterName = "checkToken", urlPatterns = "/*")
class CheckTokenFilter implements Filter {


    @Override
    void init(FilterConfig filterConfig) throws ServletException {
        log.info("CheckTokenFilter init...")
    }

    @Override
    void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest
        HttpServletResponse response = (HttpServletResponse) servletResponse

        if(request.getRequestURI().endsWith("/login") || request.getRequestURI().endsWith("/loginForm")){
            //登陆接口不校验token，直接放行
            chain.doFilter(request, response)
            return
        }

        //其他API接口一律校验token
        //从请求头中获取token
        String token = request.getHeader("token")


        Map<String, Object> resultMap = Jwt.validToken(token)
        TokenState state = TokenState.getTokenState((String)resultMap.get("state"))

        switch (state) {
            case VALID:
                //取出payload中数据,放入到request作用域中
                request.setAttribute("data", resultMap.get("data"))
                //放行
                chain.doFilter(request, response)
                return
            case EXPIRED:
            case INVALID:
            default:
                //token过期或者无效，则输出错误信息返回给ajax
                JSONObject outputMSg=new JSONObject()
                outputMSg.put("success", false)
                outputMSg.put("msg", "您的token不合法或者过期了，请重新登陆")
                output(outputMSg.toJSONString(), response)
                return
        }

    }

    @Override
    void destroy() {
        log.info("CheckTokenFilter destroy...")
    }

    void output(String jsonStr,HttpServletResponse response) throws IOException{
        response.setContentType("text/html;charset=UTF-8;")
        PrintWriter out = response.getWriter()
        out.write(jsonStr)
        out.flush()
        out.close()
    }
}
